package common

import (
	"os"
	"strings"
	"sync"
)

func SubstringAfter(str string, delimiter byte, isLast bool) string {
	lastSlashIndex := TernaryOperator(isLast, func() int { return strings.LastIndexByte(str, delimiter) }, func() int { return strings.IndexByte(str, delimiter) })
	if lastSlashIndex >= 0 {
		return strings.TrimLeft(str[lastSlashIndex:], string(delimiter))
	}
	return str
}

func SubstringBefare(str string, delimiter byte, isLast bool) string {
	lastSlashIndex := TernaryOperator(isLast, func() int { return strings.LastIndexByte(str, delimiter) }, func() int { return strings.IndexByte(str, delimiter) })
	if lastSlashIndex >= 0 {
		return strings.TrimRight(str[:lastSlashIndex], string(delimiter))
	}
	return str
}

func TernaryOperator[T any](is bool, tr func() T, fl func() T) T {
	if is {
		return tr()
	} else {
		return fl()
	}
}

var mu sync.RWMutex

// 写操作加锁
func Set[T comparable, V any](m map[T]V, key T, value V) {
	mu.Lock()
	defer mu.Unlock()
	m[key] = value
}

// 读操作加读锁
func Get[T comparable, V any](m map[T]V, key T) V {
	mu.RLock()
	defer mu.RUnlock()
	return m[key]
}

func DirectoryExists(path string) (exists bool, isDir bool, err error) {
	info, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			return false, false, nil
		}
		return false, false, err
	}
	return true, info.IsDir(), nil
}

// 从URL中提取文件名（简单实现）
func ExtractFilename(url string) string {
	// 1. 移除查询参数和锚点（?和#之后的部分）
	if idx := strings.Index(url, "?"); idx != -1 {
		url = url[:idx]
	}
	if idx := strings.Index(url, "#"); idx != -1 {
		url = url[:idx]
	}
	lastSlashIndex := strings.LastIndexByte(url, '/')
	if lastSlashIndex >= 0 {
		// 提取最后一个斜杠后的内容，并移除左侧可能存在的斜杠
		resourceName := strings.TrimLeft(url[lastSlashIndex:], "/")
		return resourceName // 输出: "resource"
	}
	return ""
}
